import { formatTime } from '../../utils/util'
const app = getApp();
let imgListUrl = []
Page({
  data: {
    publisher:'',   // 发布者
    avatar: '',
    lostTitle: '',  // 标题
    time: '选择时间',  // 发布时间
    date: '2021-05-06',   // 发布日期
    imgList: [],         // 照片
    description: '',
    tag:"寻物",
    phone: '',   // 电话号码
    publishTime: ''
  },
  onLoad(){
    let userInfo = wx.getStorageSync('userInfo')
    this.setData({
      publisher: userInfo.userName,
      avatar: userInfo.avatar
    })
    let date = new Date()
    let submitTime = formatTime(date)
    this.setData({
      publishTime: submitTime,
      date: submitTime
    })
  },


  // PickerChange(e) {
  //   console.log(e);
  //   this.setData({
  //     index: e.detail.value
  //   })
  // },
 
 
  ChooseImage() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除这张照片吗？',
      cancelText: '再看看',
      confirmText: '是的',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
 
  descInput(e) {
    this.setData({
      description: e.detail.value
    })
  },

  typeChange(e){
    // console.log(e.detail.value)
    if(e.detail.value){
      this.setData({
        tag: "寻物"
      })
    }else{
      this.setData({
        tag: "招领"
      })
    }
  },


  titleChange(e){
    this.setData({
      lostTitle: e.detail.value
    })
  },
  publisherChange(e){
    this.setData({
      publisher: e.detail.value
    })
  },
  TimeChange(e) {
    this.setData({
      time: e.detail.value
    })
  },
  DateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },

  phoneChange(e){
    this.setData({
      phone: e.detail.value
    })
  },
  submit(){
    wx.showLoading({
      title: '提交中',
    })
    // console.log(this.data)
    this.getUrl()
  },

  getUrl(){
    let promiseArr = []
     //  1, 将图片插到 云存储
     this.data.imgList.forEach((item,idx) => {
      let p = new Promise((resolve, reject)=>{
        wx.cloud.uploadFile({
          cloudPath: "lost-img/" + Date.now() + '.jpg',
          filePath: item
        }).then(
          res=> {
            // console.log(res.fileID)
            wx.cloud.getTempFileURL({
              fileList: [{
                fileID: res.fileID,
                maxAge: 60 * 60, // one hour
              }]
            }).then(res => {
              // get temp file URL
              // console.log(res.fileList[0].tempFileURL)
              // imgListUrl = this.data.imgListUrl
              imgListUrl.push(res.fileList[0].tempFileURL)
              // console.log(res.fileList[0].tempFileURL)
              this.setData({
                imgListUrl
              })
              resolve()
            })
          }
        )
      })
      promiseArr.push(p)
    })
    
    Promise.all(promiseArr).then(res => {
      // console.log(imgListUrl)
      this.addlostFoundList()
    })
  },

  addlostFoundList(){
    wx.cloud.callFunction({
      name: 'addlost',
      data:{
        tag: this.data.tag,
        title: this.data.lostTitle,
        description: this.data.description,
        imageUrl: this.data.imgListUrl[0]
      }
    }).then(res=>{
      // console.log()
      this.addlostDetail(res.result._id)
    })
  },

  addlostDetail(val){
    wx.cloud.callFunction({
      name:"addlostDetails",
      data:{
        _id: val,
        avatarImageUrl: this.data.avatar,
        desc: this.data.description,
        imageUrl: this.data.imgListUrl,
        likes: 0,
        publishTime: this.data.publishTime,
        publisher: this.data.publisher,
        phone: this.data.phone
      }
    }).then(res=>{

      wx.hideLoading({
        success: (res) => {},
      })
      wx.showToast({
        title: '成功发布!',
      }).then(()=>{
        wx.switchTab({
          url:  "/pages/lost-found/index",
        })
      })
    })
  }
})